package handler

import (
	"context"
	"gitee.com/fangy1111/shop/userop"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"userop_srv/global"
	"userop_srv/model"
)

// 用户收藏列表
func (u UserOpServer) GetFavList(ctx context.Context, request *userop.UserFavRequest) (*userop.UserFavListResponse, error) {
	var userFav []*model.UserFav
	tx := global.DB.Model(&model.UserFav{}).Where(model.UserFav{
		UserId: request.UserId,
	}).Find(&userFav)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "获取收藏列表失败")
	}

	var userFavInfo []*userop.UserFavResponse

	for _, fav := range userFav {
		userFavInfo = append(userFavInfo, &userop.UserFavResponse{
			UserId:  fav.UserId,
			GoodsId: fav.GoodsId,
		})
	}

	var count int64

	global.DB.Model(&model.UserFav{}).Where(model.UserFav{
		UserId: request.UserId,
	}).Count(&count)

	return &userop.UserFavListResponse{
		Total: int32(count),
		Data:  userFavInfo,
	}, nil
}

// 添加用户收藏
func (u UserOpServer) AddUserFav(ctx context.Context, request *userop.UserFavRequest) (*userop.UserFavEmpty, error) {
	userfav := model.UserFav{
		UserId:  request.UserId,
		GoodsId: request.GoodsId,
	}
	tx := global.DB.Model(&model.UserFav{}).Create(&userfav)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "收藏失败")
	}
	return &userop.UserFavEmpty{}, nil
}

// 删除用户收藏
func (u UserOpServer) DeleteUserFav(ctx context.Context, request *userop.UserFavRequest) (*userop.UserFavEmpty, error) {
	var userFav model.UserFav
	tx := global.DB.Model(&model.UserFav{}).Where(model.UserFav{
		UserId:  request.UserId,
		GoodsId: request.GoodsId,
	}).Delete(&userFav)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "删除收藏失败")
	}

	return &userop.UserFavEmpty{}, nil
}

// 获取用户收藏详情
func (u UserOpServer) GetUserFavDetail(ctx context.Context, request *userop.UserFavRequest) (*userop.UserFavRequest, error) {
	var userFav model.UserFav
	tx := global.DB.Model(&model.UserFav{}).Where(model.UserFav{
		UserId:  request.UserId,
		GoodsId: request.GoodsId,
	}).First(&userFav)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "获取收藏详情失败")
	}
	return &userop.UserFavRequest{
		UserId:  userFav.UserId,
		GoodsId: userFav.GoodsId,
	}, nil
}
